package org.example.memora.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.xb.xsdschema.AppinfoDocument;
import org.example.memora.common.result.Result;
import org.example.memora.common.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口,用于OSS对象存储
 */
@Slf4j
@RestController
@RequestMapping ("/api/common")
@Tag(name = "通用接口", description = "提供阿里云OSS文件上传等接口")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @Operation(summary = "文件上传", description = "上传文件到阿里云OSS")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "上传成功"),
            @ApiResponse(responseCode = "401", description = "用户未登录"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping ("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file){
        log.info("文件上传：{}", file);
        if (file == null || file.isEmpty()) {
            log.info("上传文件为空");
            return Result.error("上传文件为空");
        }
        log.info("文件上传：{}",file);
        try {
            String originalFileName=file.getOriginalFilename();
            String extendsion=originalFileName .substring(originalFileName .lastIndexOf(".") );
            String objectName= UUID.randomUUID() .toString() +extendsion ;
            String filePath=aliOssUtil.upload(file.getBytes() ,objectName);
            return Result.success(filePath) ;
        } catch (IOException e) {
            log.info("文件上传失败:{}",e);
            throw new RuntimeException(e);
        }
        //注意配置文件里endpoint: oss-cn-beijing.aliyuncs.com，oss前面没有https://
    }
}
